/**
 * @Author: zhi1hw hanwei@zhi1tech.com
 * @Date: 2024-07-06 13:51:13
 * @LastEditors: zhi1hw hanwei@zhi1tech.com
 * @LastEditTime: 2024-07-13 11:39:31
 * @FilePath: \code\src\views\common\soundRecording.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import React, { useState, useRef, useEffect, useContext } from 'react';
import { Popup } from 'react-vant'; // 替代 van-popup
import keyboardIcon from '@/assets/images/keyboard-icon.png';
import language from '@/lang/zh';
import { ThemeContext } from '@/context/ThemeContext'; // 假设您创建了ThemeContext

const SoundRecording = (props) => {
  const themeColor = useContext(ThemeContext);
  const [show, setShow] = useState(false);
  const [state, setState] = useState({
    loop: '',
    btRecoding: false,
    blackBoxSpeak: true,
    startY: 0,
    timeOutEvent: 0,
    isSoundRecording: false,
    showBottom: false,
    isDisabled: false
  });
  
  const loaderRef = useRef(null);

  const updateState = (newState) => {
    setState(prevState => ({ ...prevState, ...newState }));
  };

  // 关闭语音按钮
  const closeVoiceButton = () => {
    props.bindChangeKeyword();
    wx.stopRecord();
  };

  // 关闭语音
  const closeVoice = () => {
    wx.stopRecord();
  };

  // 手指开始触发
  const touchstart = (e) => {
    const startY = e.targetTouches[0].clientY;
    updateState({ startY });
    
    clearTimeout(state.timeOutEvent);
    
    const timeoutId = setTimeout(() => {
      console.log(456);
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: [
            'translateVoice',
            'stopRecord',
            'startRecord'
          ],
          success: function(res) {
            if(!res.checkResult.translateVoice || !res.checkResult.stopRecord || !res.checkResult.startRecord) {
              // 假设有一个显示toast的函数
              alert("语音功能仅支持在企业微信中使用，需要使用此功能请前往企业微信 -> 工作台 -> 小助手中打开应用");
            } else {
              updateState({ showBottom: true });
              startRecord();
            }
          }
        });
      });
    }, 500);
    
    updateState({ timeOutEvent: timeoutId });
    return false;
  };

  // 长按超过500毫秒，开始录音
  const startRecord = () => {
    updateState({ isSoundRecording: true });
    wx.startRecord();
  };

  // 短按
  const startRecordClick = () => {
    // 长按没有超过500毫秒
  };

  // 手指离开屏幕触发
  const touchend = () => {
    clearTimeout(state.timeOutEvent);
    if (state.timeOutEvent === 0) {
      updateState({ btRecoding: true });
      startRecordClick();
    } else {
      updateState({ 
        btRecoding: false,
        isSoundRecording: false 
      });
      stopRecord();
    }
  };

  // 滑动触发
  const touchmove = (e) => {
    const endY = e.targetTouches[0].clientY;
    if (state.startY - 30 < endY) {
      updateState({ blackBoxSpeak: true });
    } else {
      updateState({ blackBoxSpeak: false });
    }
  };

  // 停止录音
  const stopRecord = () => {
    wx.stopRecord({
      success: function (res) {
        const localId = res.localId;
        updateState({ showBottom: false });
        
        if (state.blackBoxSpeak) {
          addVoiceItems(localId);
        } else {
          updateState({ blackBoxSpeak: true });
        }
      },
    });

    updateState({ isSoundRecording: false });
  };

  // 通知父元素插入问答数据
  const addVoiceItems = (id) => {
    wx.translateVoice({
      localId: id,
      isShowProgressTips: 1,
      success: function (res) {
        const obj = {
          text: res.translateResult,
          type: 0,
          itemType: "voice",
        };
        props.addVoiceItem(obj);
        props.bindChangeKeyword();
      },
    });
  };

  return (
    <>
      <div 
        className="voice-input" 
        onTouchStart={touchstart} 
        onTouchEnd={touchend} 
        onTouchMove={touchmove}
      >
        <div>
          {state.isSoundRecording 
            ? (props.stateSound ? language.messageEN.send : language.messageZH.send) 
            : (props.stateSound ? language.messageEN.talk : language.messageZH.talk)
          }
        </div>
        <span>
          {!state.isDisabled && (
            <img
              className="other-yuyin"
              src={keyboardIcon}
              alt=""
              onClick={closeVoiceButton}
            />
          )}
        </span>
      </div>
      
      <Popup
        visible={state.showBottom}
        round
        position="bottom"
        className="modal-class"
        safeAreaInsetBottom
        style={{ height: '30%' }}
        onClose={closeVoice}
      >
        <div className="sound-recording">
          <div className="sound-recording-box">
            <p>{props.stateSound ? language.messageEN.listen : language.messageZH.listen}</p>
            <p>
              {state.isSoundRecording 
                ? (props.stateSound ? language.messageEN.release : language.messageZH.release) 
                : (props.stateSound ? language.messageEN.swipe : language.messageZH.swipe)
              }
            </p>
          </div>
          <div
            className={`loaderbg loader ${!state.blackBoxSpeak ? 'loaderbg1' : ''}`}
            ref={loaderRef}
          >
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </Popup>
      
      <style jsx>{`
        .area-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          color: ${themeColor.textColorLighten};
          font-size: 24px;
        }
        .area-item img {
          width: 86px;
          margin-bottom: 10px;
          border: 1px dashed ${themeColor.borderColorLighten};
          pointer-events: none;
        }
        .voice-input {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);
        }
        .voice-input div {
          font-size: 32px;
          font-weight: 700;
          letter-spacing: 0px;
          line-height: 44.8px;
          color: rgba(40, 51, 74, 1);
          text-align: left;
          vertical-align: top;
          margin: 0 auto;
        }
        .voice-input img {
          display: flex;
          width: 60px;
        }
        .sound-recording-box p {
          display: block;
          text-align: center;
        }
        .sound-recording-box > p:first-child {
          font-size: 32px;
          font-weight: 700;
          letter-spacing: 0px;
          line-height: 44.8px;
          color: rgba(40, 51, 74, 1);
          text-align: center;
          vertical-align: top;
          margin: 68px 0 48px 0;
        }
        .sound-recording-box > p:last-child {
          font-size: 28px;
          font-weight: 500;
          letter-spacing: 0px;
          line-height: 58px;
          color: rgba(148, 162, 176, 1);
          text-align: center;
          vertical-align: top;
        }
        .modal-class {
          padding: 0 30px;
          padding-bottom: constant(safe-area-inset-bottom);
          padding-bottom: env(safe-area-inset-bottom);
        }
        .modal-class .loader,
        .modal-class .loaderbg {
          margin: auto;
          width: calc(100% - 60px);
          height: 96px;
          display: flex;
          justify-content: center;
          opacity: 1;
          border-radius: 10px;
          background: rgba(92, 178, 255, 0.1);
          align-items: center;
          position: absolute;
          bottom: 100px;
        }
        .modal-class .loader span,
        .modal-class .loaderbg span {
          display: block;
          background: rgba(92, 178, 255, 1);
          width: 7px;
          height: 10%;
          border-radius: 14px;
          margin-right: 14px;
          float: left;
          margin-top: 0;
        }
        .modal-class .loaderbg1 {
          background: rgba(237, 28, 36, 0.1);
        }
        .modal-class .loaderbg1 span {
          background: rgba(237, 28, 36, 1);
        }
        .modal-class .loader span:last-child {
          margin-right: 0px;
        }
        .modal-class .loader span:nth-child(1) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.4s infinite linear;
        }
        .modal-class .loader span:nth-child(2) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.2s infinite linear;
        }
        .modal-class .loader span:nth-child(3) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1s infinite linear;
        }
        .modal-class .loader span:nth-child(4) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.8s infinite linear;
        }
        .modal-class .loader span:nth-child(5) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.6s infinite linear;
        }
        .modal-class .loader span:nth-child(6) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.4s infinite linear;
        }
        .modal-class .loader span:nth-child(7) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.2s infinite linear;
        }
        .modal-class .loader span:nth-child(8) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0s infinite linear;
        }
        .modal-class .loader span:nth-child(9) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.2s infinite linear;
        }
        .modal-class .loader span:nth-child(10) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.4s infinite linear;
        }
        .modal-class .loader span:nth-child(11) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.6s infinite linear;
        }
        .modal-class .loader span:nth-child(12) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.8s infinite linear;
        }
        .modal-class .loader span:nth-child(13) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1s infinite linear;
        }
        .modal-class .loader span:nth-child(14) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.2s infinite linear;
        }
        .modal-class .loader span:nth-child(15) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.4s infinite linear;
        }
        .modal-class .loader span:nth-child(16) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.4s infinite linear;
        }
        .modal-class .loader span:nth-child(17) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.2s infinite linear;
        }
        .modal-class .loader span:nth-child(18) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1s infinite linear;
        }
        .modal-class .loader span:nth-child(19) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.8s infinite linear;
        }
        .modal-class .loader span:nth-child(20) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.6s infinite linear;
        }
        .modal-class .loader span:nth-child(21) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.4s infinite linear;
        }
        .modal-class .loader span:nth-child(22) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.2s infinite linear;
        }
        .modal-class .loader span:nth-child(23) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0s infinite linear;
        }
        .modal-class .loader span:nth-child(24) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.2s infinite linear;
        }
        .modal-class .loader span:nth-child(25) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.4s infinite linear;
        }
        .modal-class .loader span:nth-child(26) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.6s infinite linear;
        }
        .modal-class .loader span:nth-child(27) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 0.8s infinite linear;
        }
        .modal-class .loader span:nth-child(28) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1s infinite linear;
        }
        .modal-class .loader span:nth-child(29) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.2s infinite linear;
        }
        .modal-class .loader span:nth-child(30) {
          --her: 10%;
          --her1: 15%;
          animation: load 2s 1.4s infinite linear;
        }
        @keyframes load {
          0% {
            height: var(--her, 10%);
          }
          100% {
            height: var(--her1, 15%);
          }
        }
      `}</style>
    </>
  );
};

SoundRecording.defaultProps = {
  stateSound: false,
  addVoiceItem: () => {},
  bindChangeKeyword: () => {}
};

export default SoundRecording;